package com.jgssp.ad.sdk.topon.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.anythink.nativead.api.ATNativePrepareInfo;
import com.anythink.nativead.unitgroup.api.CustomNativeAd;

import java.util.List;

import cn.jiguang.jgssp.ad.data.ADJgNativeAdInfo;
import cn.jiguang.jgssp.ad.data.ADJgNativeExpressAdInfo;
import cn.jiguang.jgssp.ad.error.ADJgError;
import cn.jiguang.jgssp.ad.listener.ADJgNativeAdListener;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 2021/12/7 5:56 PM
 */
public class NativeExpressAd extends CustomNativeAd implements ADJgNativeAdListener {
    private ADJgNativeExpressAdInfo nativeExpressAdInfo;
    private View mMediaView;

    public NativeExpressAd(Context context, ADJgNativeExpressAdInfo nativeExpressAdInfo) {
        this.nativeExpressAdInfo = nativeExpressAdInfo;
    }

    @Override
    public boolean isNativeExpress() {
        return true;
    }

    @Override
    public void onRenderFailed(ADJgNativeAdInfo adJgNativeAdInfo, ADJgError adJgError) {

    }

    @Override
    public void onRenderSuccess(ADJgNativeAdInfo adJgNativeAdInfo) {

    }

    @Override
    public void onAdReceive(List<ADJgNativeAdInfo> list) {

    }

    @Override
    public void onAdExpose(ADJgNativeAdInfo adJgNativeAdInfo) {
        notifyAdImpression();
    }

    @Override
    public void onAdClick(ADJgNativeAdInfo adJgNativeAdInfo) {
        notifyAdClicked();
    }

    @Override
    public void onAdClose(ADJgNativeAdInfo adJgNativeAdInfo) {
        notifyAdDislikeClick();
    }

    @Override
    public void onAdFailed(ADJgError adJgError) {

    }

    @Override
    public void prepare(View view, ATNativePrepareInfo nativePrepareInfo) {
        super.prepare(view, nativePrepareInfo);
        renderExpressAd(view);
    }

    @Override
    public View getAdMediaView(Object... object) {
        try {
            if (mMediaView == null && nativeExpressAdInfo != null && object[0] != null && object[0] instanceof ViewGroup) {
                ViewGroup container = (ViewGroup) object[0];
                container.removeAllViews();
                mMediaView = nativeExpressAdInfo.getNativeExpressAdView(container);
            }
            return mMediaView;
        } catch (Exception e) {

        }
        return null;
    }

    public void renderExpressAd(View view) {
        if (nativeExpressAdInfo != null && view != null) {
            FrameLayout viewGroup = new FrameLayout(view.getContext());
            nativeExpressAdInfo.render(viewGroup);
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        mMediaView = null;
        if (nativeExpressAdInfo != null) {
            nativeExpressAdInfo.release();
            nativeExpressAdInfo = null;
        }
    }

}
